import { Button, message } from 'antd'
import ChooseGroupsToJoin from '@/desktop/components/ChooseGroupsToJoin'
import services from '@/services'
import { type Contact } from '@/services/contacts'
import './ToExistGroup.module.less'

export default function PullInExistGroup(props: { contact: Contact; onFinish: () => void }) {
  const { contact, onFinish } = props

  const [choosed, setChoosed] = useState<string[]>([])

  const [submitting, setSubmitting] = useState(false)
  const submit = useCallback(async () => {
    setSubmitting(true)
    for (const groupId of choosed) {
      const res = await services.groups.pullIn(groupId, contact.userId) // eslint-disable-line no-await-in-loop
      if (!res.success) void message.error(`拉群失败：${res.error}`)
    }

    void message.success('拉群完成')
    onFinish()
  }, [contact, choosed, onFinish])

  return <main>
    <div styleName="content">
      <ChooseGroupsToJoin wxids={contact.ownerWxid} choosed={choosed} setChoosed={setChoosed} />
    </div>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" onClick={submit} disabled={!choosed.length} loading={submitting}>
        确定
      </Button>
    </footer>
  </main>
}
